// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "api.h"
#include "azure_c_shared_utility/optimize_size.h"
#include "azure_c_shared_utility/tickcounter.h"

class TICK_COUNTER_INSTANCE_TAG
{
public:
    tickcounter_ms_t current_ms;
};

TICK_COUNTER_HANDLE tickcounter_create(void)
{
    TICK_COUNTER_INSTANCE_TAG* result;
    result = new TICK_COUNTER_INSTANCE_TAG();
    result->current_ms = xos::TickGet();
    return result;
}

void tickcounter_destroy(TICK_COUNTER_HANDLE tick_counter)
{
    if (tick_counter != NULL)
    {
        delete tick_counter;
    }
}

int tickcounter_get_current_ms(TICK_COUNTER_HANDLE tick_counter, tickcounter_ms_t * current_ms)
{
    int result;
	TICK_COUNTER_INSTANCE_TAG* tick_counter_instance = (TICK_COUNTER_INSTANCE_TAG*)tick_counter;

    if (tick_counter == NULL)
    {
        result = __FAILURE__;
    }
	else if (current_ms == (tickcounter_ms_t *)-1) {
		tick_counter_instance->current_ms = xos::TickGet();
	}
	else if (current_ms == NULL) {

		tickcounter_ms_t  clock_value = xos::TickGet();

		result = clock_value - tick_counter_instance->current_ms;

	}
    else
    {
		tickcounter_ms_t  clock_value = xos::TickGet();

        *current_ms = clock_value - tick_counter_instance->current_ms;

        result = 0;
    }
    return result;
}
